require(mxnet)

context("ndarray")

test_that("element-wise calculation for vector", {
  x = 1:10
  mat = mx.nd.array(as.array(x), mx.cpu(0))
  expect_equal(x, as.array(mat))
  expect_equal(x+1, as.array(mat+1))
  expect_equal(x-10, as.array(mat-10))
  expect_equal(x*20, as.array(mat*20))
  expect_equal(x/3, as.array(mat/3), tolerance = 1e-5)
  expect_equal(-1-x, as.array(-1-mat))
  expect_equal(-5/x, as.array(-5/mat), tolerance = 1e-5)
  expect_equal(x+x, as.array(mat+mat))
  expect_equal(x/x, as.array(mat/mat))
  expect_equal(x*x, as.array(mat*mat))
  expect_equal(x-x, as.array(mat-mat))
  expect_equal(as.array(1-mat), as.array(1-mat))
})

test_that("element-wise calculation for matrix", {  
  x = matrix(1:4, 2, 2)
  mat = mx.nd.array(as.array(x), mx.cpu(0))
  expect_equal(x, as.array(mat))
  expect_equal(x+1, as.array(mat+1))
  expect_equal(x-10, as.array(mat-10))
  expect_equal(x*20, as.array(mat*20))
  expect_equal(x/3, as.array(mat/3), tolerance = 1e-5)
  expect_equal(-1-x, as.array(-1-mat))
  expect_equal(-5/x, as.array(-5/mat), tolerance = 1e-5)
  expect_equal(x+x, as.array(mat+mat))
  expect_equal(x/x, as.array(mat/mat))
  expect_equal(x*x, as.array(mat*mat))
  expect_equal(x-x, as.array(mat-mat))
  expect_equal(as.array(1-mat), as.array(1-mat))
})

test_that("ndarray ones, zeros, save and load", {
  expect_equal(rep(0, 10), as.array(mx.nd.zeros(10)))
  expect_equal(matrix(0, 10, 5), as.array(mx.nd.zeros(c(10, 5))))
  expect_equal(rep(1, 10), as.array(mx.nd.ones(10)))
  expect_equal(matrix(1, 10, 5), as.array(mx.nd.ones(c(10, 5))))
  mat = mx.nd.array(1:20)
  mx.nd.save(mat, 'temp.mat')
  mat2 = mx.nd.load('temp.mat')
  expect_true(is.mx.ndarray(mat2[[1]]))
  expect_equal(as.array(mat), as.array(mat2[[1]]))
})
